import React, { Component } from 'react';
import {
    Text,
    StyleSheet,
    View,
    TextInput,
    Dimensions,
    Button,
    Image,
} from 'react-native';

const { width, height } = Dimensions.get('screen');
const rpx = x => (width / 750) * x;

export default class LoginScreen extends Component {
    state = { uname: '', upwd: '' };

    render() {
        return (
            <View style={{ alignItems: 'center' }}>
                <View style={{ width: rpx(550), marginTop: rpx(100) }}>
                    <TextInput
                        style={ss.input}
                        placeholder="请输入管理员用户名"
                        value={this.state.uname}
                        onChangeText={uname => this.setState({ uname })}
                    />
                    <View style={{ height: rpx(20) }} />
                    <TextInput
                        secureTextEntry
                        style={ss.input}
                        placeholder="请输入用户登录密码"
                        value={this.state.upwd}
                        onChangeText={upwd => this.setState({ upwd })}
                    />
                    <View style={{ height: rpx(60) }} />
                    <Button title="登录" onPress={this.doLogin} />

                    <View style={ss.area_logo}>
                        <Image source={require('../assets/logo.png')} />
                        <Text style={{ fontSize: rpx(40) }}>后台管理系统</Text>
                    </View>
                    <Text style={{ textAlign: 'center', marginTop: rpx(80) }}>
                        ©2017 版权所有, CODEBOY.COM
          </Text>
                </View>
            </View>
        );
    }

    doLogin = () => {
        // 正常: 先发送请求, 登录成功后进行跳转操作
        // 由于登录请求时 POST方式, 
        // 暂时就直接跳转即可
        // this.props.navigation.push('Main');
        const { upwd, uname } = this.state;
        console.log(uname, upwd);

        // POST请求: 与 GET 不同,  路由和参数 需要分开发送
        const url = 'http://101.96.128.94:9999/data/user/login.php';
        const body = `uname=${uname}&upwd=${upwd}`;

        // 文档:https://www.react-native.cn/docs/network

        // 用户名:doudou  密码:123456
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body,
        })
            .then(res => res.json())
            .then(res => {
                console.log(res);
                if (res.code == 200) {
                    this.props.navigation.push('Main');
                } else {
                    alert('登录失败!');
                }
            });
    };
}

const ss = StyleSheet.create({
    input: {
        fontSize: rpx(36),
        color: 'black',
        borderBottomWidth: rpx(1),
    },
    area_logo: {
        marginTop: rpx(60),
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
    },
});
